package com.neuedu.web.filter;


import com.neuedu.web.utils.JSONUtils;
import com.neuedu.web.common.Res;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 金山
 * 项目：javaweb
 * site: https://blog.fulfill.com.cn
 * 描述
 * @data 2024/11/1511:49
 */
// @WebFilter(urlPatterns = "/*")
// @WebFilter(value = "/*")
@WebFilter( "/*")
public class LoginFilter  implements Filter {


    //白名单
    String whiteList = "/login";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // System.out.println("EncodingFilter.init");
    }

    /**
     * 执行的 过滤 核心代码
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        /**
         * 忽略的白名单
         */
        //请求路径
        String requestURI = request.getRequestURI();

        requestURI = requestURI.substring(requestURI.lastIndexOf("/"));
        boolean isWhiteList = whiteList.indexOf(requestURI) != -1;

        // 判断是否登录
        HttpSession session = request.getSession();
        String id = session.getId();
        Object userName = session.getAttribute("userName");
        if(userName != null || isWhiteList){
            //Filter 链 方形
            filterChain.doFilter(servletRequest,servletResponse);
        }else{

            JSONUtils.write(response, Res.unauthorized());
        }

    }


}
